"""
任务管理API路由
提供RESTful API接口
"""

from loguru import logger
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import StreamingResponse

from app.models.task.task_request import TaskRequest, TaskResponse
from app.models.task.task_data import TaskStatus, TaskType
from app.services.task_service import task_manager
from app.core.sse_manager import sse_manager
from app.core.task_scheduler.task_registry import task_registry

router = APIRouter(tags=["tasks"])


@router.post("/tasks", response_model=TaskResponse)
async def create_task(request: TaskRequest):
    """创建新任务"""
    try:
        response = await task_manager.create_task(request)
        return response
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"创建任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建任务失败")


@router.get("/tasks/stats")
async def get_task_stats():
    """获取任务统计信息"""
    try:
        stats = await task_manager.get_stats()
        return stats
    except Exception as e:
        logger.error(f"获取统计信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取统计信息失败")


@router.post("/tasks/cleanup")
async def cleanup_completed_tasks():
    """清理已完成的任务"""
    try:
        deleted_count = await task_manager.cleanup()
        return {"message": f"已清理 {deleted_count} 个任务"}
    except Exception as e:
        logger.error(f"清理任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="清理任务失败")


@router.get("/tasks", response_model=List[TaskResponse])
async def list_tasks(
    status: Optional[TaskStatus] = None,
    task_type: Optional[TaskType] = None,
    limit: int = 100,
):
    """获取任务列表"""
    try:
        tasks = await task_manager.list_tasks(status, task_type, limit)
        return tasks
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务列表失败")


@router.get("/tasks/{task_id}", response_model=TaskResponse)
async def get_task(task_id: str):
    """获取单个任务信息"""
    try:
        task = await task_manager.get_task(task_id)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        return task
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务失败")


@router.delete("/tasks/{task_id}")
async def cancel_task(task_id: str):
    """取消任务"""
    try:
        success = await task_manager.cancel_task(task_id)
        if not success:
            raise HTTPException(status_code=400, detail="无法取消该任务")
        return {"message": "任务已取消", "task_id": task_id}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"取消任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="取消任务失败")


@router.get("/functions")
async def list_functions():
    """获取已注册的函数列表"""
    try:
        functions = task_registry.list_registered_tasks()
        return {"functions": functions}
    except Exception as e:
        logger.error(f"获取函数列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取函数列表失败")


@router.get("/sse/events")
async def sse_endpoint(request: Request):
    """SSE事件流端点"""
    try:
        client_id = sse_manager.add_client(request)

        async def event_stream():
            async for message in sse_manager.get_client_stream(client_id):
                yield message

        return StreamingResponse(
            event_stream(),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Cache-Control",
            },
        )
    except Exception as e:
        logger.error(f"SSE连接失败: {str(e)}")
        raise HTTPException(status_code=500, detail="SSE连接失败")


@router.get("/sse/clients")
async def get_sse_clients():
    """获取SSE客户端信息"""
    try:
        clients_info = sse_manager.get_clients_info()
        return clients_info
    except Exception as e:
        logger.error(f"获取客户端信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取客户端信息失败")


@router.get("/tasks/{task_id}/progress")
async def get_task_progress(task_id: str):
    """获取任务当前进度（HTTP轮询方式）"""
    try:
        task = await task_manager.get_task(task_id)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")

        return {
            "task_id": task_id,
            "progress": getattr(task, "progress", 0.0),
            "status": task.status,
            "name": task.name,
            "created_at": task.created_at,
            "started_at": task.started_at,
            "completed_at": task.completed_at,
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取任务进度失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务进度失败")


@router.get("/tasks/{task_id}/progress/stream")
async def get_task_progress_stream(request: Request, task_id: str):
    """获取任务进度的SSE流（实时推送）"""
    try:
        # 检查任务是否存在
        task = await task_manager.get_task(task_id)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")

        return StreamingResponse(
            await sse_manager.get_task_progress_stream(request, task_id),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Cache-Control",
            },
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建任务进度流失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建任务进度流失败")


@router.get("/progress/stream")
async def get_all_progress_stream(request: Request):
    """获取所有任务进度的SSE流"""
    try:
        return StreamingResponse(
            await sse_manager.get_all_progress_stream(request),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Cache-Control",
            },
        )
    except Exception as e:
        logger.error(f"创建进度流失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建进度流失败")


@router.post("/tasks/{task_id}/cancel")
async def cancel_task_endpoint(task_id: str):
    """取消正在执行的任务"""
    try:
        success = await task_manager.cancel_task(task_id)
        if success:
            return {"message": f"任务 {task_id} 已成功取消"}
        else:
            raise HTTPException(status_code=400, detail="任务无法取消")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"取消任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="取消任务失败")
